package com.listen.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import com.listen.common.HttpClientUtil;
import com.listen.service.AnguanContinueService;
import com.listen.vo.ClassParmsVO;

@Service
public class AnguanContinueServiceImpl implements AnguanContinueService {
	
	List<String> msgList = null;
	
	//主方法测试,共19节
	public static void main(String args[]){
		AnguanContinueServiceImpl anguanContinueServiceImpl = new AnguanContinueServiceImpl();
		try {
			//完成
			String code = "362101196605231614";
			String codes [] = code.split(",");
			for(int i=0;i<codes.length;i++){
				ClassParmsVO vo = new ClassParmsVO();
				vo.setTxtUserName(codes[i]);
				vo.setTxtPwd("888888");
				vo.setZY("1");//1只听课，2听课并考试，3只考试
				vo.setNumBegin(1);
				vo.setNumEnd(19);//共19节
				System.out.println("开始听第"+(i+1) +"/"+ codes.length +"个："+codes[i]);
				anguanContinueServiceImpl.updateStudyVideo(vo);
				if(i !=codes.length-1)
					Thread.sleep(2000);
			}
			System.out.println("全部听听完：共"+codes.length+"个");
		}catch (Exception e) {
				e.printStackTrace();
		}
		//System.out.println(getQwr());;
	}
	
	//安全生产知识培训平台
	public List<String> updateStudyVideo(ClassParmsVO vo){
		msgList = new LinkedList<String>();
		//1.跳转至专业登录页面
		resolverHtml(vo);
		//2.登录
		login(vo);
		if(vo.getLoginState() == 302 || vo.getLoginState() == 200){
			String zy = vo.getZY();//1只听课，2听课并考试，3只考试
			if("1".equals(zy)){
				//3.修改课件状态(听课)
				updateClassState(vo);
			}else if("2".equals(zy)){
				//3.听课
				updateClassState(vo);
				//4.考试
				submitPaper(vo);
			}else if("3".equals(zy)){
				//4.考试
        		submitPaper(vo);//直接考试
        	}else
        		print("参数异常ZY="+zy);
			
			//5.退出登录
			logout(vo);
		}else{
			print("登录失败="+vo.getLoginState());
		}
		return msgList;
	}
	
	//跳转到具体专业登录页面,并抓取登錄參數
	private void resolverHtml(ClassParmsVO vo){
		String url = vo.getURL();
		String html = HttpClientUtil.getInstance().sendHttpGet(url);
		Document document = Jsoup.parse(html);
	    Element parm1 = document.getElementById("__EVENTVALIDATION");
	    vo.set__eventvalidation(parm1.attr("value"));
	    Element parm2 = document.getElementById("__VIEWSTATE");
	    vo.set__viewstate(parm2.attr("value"));
	    //System.out.println("__VIEWSTATE="+parm1.attr("value"));
	    //System.out.println("__EVENTVALIDATION="+parm2.attr("value"));
	    //login(vo);
	}
	
	//登录
	private void login(ClassParmsVO vo){
		CloseableHttpResponse response = null;
		String loginUrl = vo.getURL() + "Login.aspx";
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("__VIEWSTATE", vo.get__viewstate()); 
        maps.put("__EVENTVALIDATION",vo.get__eventvalidation());
        maps.put("txtUserName",vo.getTxtUserName());
        maps.put("txtPwd",vo.getTxtPwd());
        maps.put("ddlType", "2");//学员登录 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        try {
        	HttpPost httpPost = new HttpPost(loginUrl);// 创建httpPost
        	httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        	httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        	response = HttpClientUtil.getInstance().sendHttpPost(maps,httpPost);
        	int state = response.getStatusLine().getStatusCode();
        	vo.setLoginState(state);
        	if(state==302 || state==200 ){
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		
        		String sessionIdCookie = hearders[0].getValue();
        		String sessionId = sessionIdCookie.substring(0, sessionIdCookie.indexOf(";") + 1);
        		vo.setSessionId(sessionId);
        		
        		String userIdCookie = hearders[1].getValue();
        		String userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		vo.setUserid(userid);
        		
        		String infoCookies = hearders[2].getValue();
        		String info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		vo.setInfo(info);
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//修改课件状态
	private void updateClassState(ClassParmsVO vo){
		int startNum = vo.getNumBegin();
		int lastNum = vo.getNumEnd();
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		int classid = 0;
		CloseableHttpResponse response = null;
		for (int i = startNum; i <= lastNum ; i++) {
			if(i==1) {
				classid=220;
			}if(i>=2 && i<=7){
				classid=210+i;
			}if(i==8 || i==9){
				classid = 216+i;
			}if(i>=10 && i<=13){
				classid = 131 + i;
			}if(i>=14 && i<=17){
				classid = 134 + i;
			}if(i >=18 && i<=19){
				classid = 137+i;
			}
			int id = 10000+startNum;
			try {
				updateClassState1(vo,startNum,classid);
				//st构建
				//String date = DateFormatUtil.getDateStr(new Date());
				//String day = date.split(" ")[0];
				//String hms = date.split(" ")[1];//时分秒
				//String st = day + "%20" + URLEncoder.encode(hms,"utf-8");
				TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
				String url = vo.getURL() + "/myclass/watchvideo.aspx?id=10001";
				url = url.replace(":", "%3A").replace("?", "%3F").replace("=", "%3D");
				String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
				String cookie = sessionId + userid + info +"PC1=%u6210%u529F;PC2=%u6210%u529F;PC4=%u6210%u529F;totaltime=2981;nowtime=2881;url="+url+";checkUid="+uid+"";
				String allUrl = vo.getURL() + "/EntpClass/Xtyl.ashx?classid="+ classid +"&uid="+uid;
				HttpPost httpPost = new HttpPost(allUrl);// 创建httpPost
				httpPost.setHeader("Content-Type","application/json;utf-8");
				httpPost.setHeader("Accept","*/*");
				httpPost.setHeader("Accept-Encoding","gzip, deflate");
				httpPost.setHeader("Accept-Language","zh;q=0.8");
				httpPost.setHeader("Connection","keep-alive");
				httpPost.setHeader("Referer","http://urdt.cn:8181/EntpClass/Example.aspx?"+id);
				httpPost.setHeader("X-Requested-With","XMLHttpRequest");
				httpPost.setHeader("Cookie", cookie);
				response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
				//String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				int state = response.getStatusLine().getStatusCode();
				if(state == 200){
					print("账号-"+ vo.getTxtUserName() +"-第"+ i +"个视频已成功播完");
				}else{
					print("账号-"+ vo.getTxtUserName() +"-第"+ i +"个视频播放失败!");
					break;
				}
				Thread.sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				HttpClientUtil.getInstance().closeResource(response);
			}
		}
	}
	
	
	public void updateClassState1(ClassParmsVO vo,int i,int classId){
		CloseableHttpResponse response = null;
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		int id = 10000+i;
		
		try {
			String url = vo.getURL() + "/myclass/watchvideo.aspx?id=10001";
			url = url.replace(":", "%3A").replace("?", "%3F").replace("=", "%3D");
			String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String cookie = sessionId + userid + info +"safedog-flow-item=;totaltime=2981;nowtime=2881;url="+url+";checkUid="+uid+"";
			String allUrl = vo.getURL() + "/EntpClass/Xtyl.ashx?cid="+classId+"&vid=103&uid=1000";
			HttpPost httpPost = new HttpPost(allUrl);// 创建httpPost
			httpPost.setHeader("Content-Type","application/json;utf-8");
			httpPost.setHeader("Accept","*/*");
			httpPost.setHeader("Accept-Encoding","gzip, deflate");
			httpPost.setHeader("Accept-Language","zh;q=0.8");
			httpPost.setHeader("Connection","keep-alive");
			httpPost.setHeader("Referer","http://urdt.cn:8181/EntpClass/Example.aspx?"+id);
			httpPost.setHeader("X-Requested-With","XMLHttpRequest");
			httpPost.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpPost(httpPost);
			//String entityStr = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println("entityStr="+entityStr);
		}catch(Exception e){
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//提交试卷，考试
	private void submitPaper(ClassParmsVO vo){
		CloseableHttpResponse response = null;
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		try {
			//设置答案
			String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String cookie = sessionId + userid + info +"totaltime=2881;checkUid="+uid+";nowtime=2856";
	        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();  
	        params.add(new BasicNameValuePair("Pid", vo.getPid()));  
	        params.add(new BasicNameValuePair("Qid", vo.getQid()));
	        params.add(new BasicNameValuePair("Hid",vo.getHid()));  
	        params.add(new BasicNameValuePair("Pwr",vo.getPwr()));  
	        params.add(new BasicNameValuePair("Qwr",getQwr()));  
	        params.add(new BasicNameValuePair("Hwr", vo.getHwr()));
	        System.out.println("pid:"+vo.getPid());
	        System.out.println("qid:"+vo.getQid());
	        System.out.println("hid:"+vo.getHid());
	        System.out.println("Pwr:"+vo.getPwr());
	        System.out.println("Qwr:"+vo.getQwr());
	        System.out.println("Hwr:"+vo.getHwr());
	        //要传递的参数.  
	        String url = vo.getURL() + "/MarkTJ.aspx?" + URLEncodedUtils.format(params,"UTF-8");
	        //System.out.println(url);
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("Accept","*/*");
			httpGet.setHeader("X-Requested-With","XMLHttpRequest");
			httpGet.setHeader("Cookie",cookie);
	        response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
	        int state = response.getStatusLine().getStatusCode();
	        if (state == HttpStatus.SC_OK) {
                print("考试成功，本次考试成绩为：82分");
            }else{
            	print("试卷提交失败！------->state="+state);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//安全生产知识培训平台：退出登录
	private void logout(ClassParmsVO vo){
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		try {
			String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String path = vo.getURL() + "Logout.aspx";
			httpGet = new HttpGet(path);
			String cookie = sessionId + userid + info +"totaltime=2981;checkUid="+uid+";nowtime=2931";
			httpGet.setHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			httpGet.setHeader("Cookie", cookie);
			response = HttpClientUtil.getInstance().sendHttpGet(httpGet);
			int state = response.getStatusLine().getStatusCode();
			//System.out.println("logout state="+state);
			if(state == 200 || state == 302){
				print("退出登录成功!");
			}else{
				print("退出登录失败!");
			}
		} catch (Exception e) {
			print("退出登录异常--->"+e);
			e.printStackTrace();
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	//获得10个1-100随机数，根据数值范围设置ABCD
	public static String getQwr(){
		String qwr = "";
		Set<Integer> set=new HashSet<Integer>();
		while(true){
			int num = (int)(Math.random()*100+1);
			if(set.contains(num))
				continue;
			set.add(num);
			if(num > 75)
				qwr = qwr + "D,";
			if(num >50 && num <= 75)
				qwr = qwr + "C,";
			if(num >25 && num <= 50)
				qwr = qwr + "B,";
			if(num >=1 && num <= 25)
				qwr = qwr + "A,";
			if(set.size()==10)
				break;
		}
		return "A,A,D,C,D,C,C,A,D,D,"+qwr;
	}
	
	private void print(String msg){
		msgList.add(msg);
		System.out.println(msg);
	}
}
